package com.weiiew.backend.utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jnativehook.keyboard.NativeKeyEvent;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @Description 快捷键管理中心
 * @Author 魏锴
 * @Date 2025/4/25
 */
@Slf4j

public class HotkeyRepository {
    // 配置目录结构
    private static final String CONFIG_FILE = "hotkeys.properties";
    private final Path configDir;
    private final Map<String, Integer> hotkeys = new ConcurrentHashMap<>();
    private final Properties defaultConfig = new Properties();

    public HotkeyRepository(Path configDir) throws IOException {
        this.configDir = configDir;
        initializeDefaults();
        createConfigDirectory();
        loadOrCreateConfig();
    }

    private void initializeDefaults() {
        // 集中管理所有默认快捷键配置
        defaultConfig.setProperty("mouse.toggle", String.valueOf(NativeKeyEvent.VC_F9));
        defaultConfig.setProperty("keyboard.toggle", String.valueOf(NativeKeyEvent.VC_F10));
        defaultConfig.setProperty("record.toggle", String.valueOf(NativeKeyEvent.VC_F8));
        defaultConfig.setProperty("record.run.toggle", String.valueOf(NativeKeyEvent.VC_F9));
        defaultConfig.setProperty("script.run.toggle", String.valueOf(NativeKeyEvent.VC_F9));
    }


    private void createConfigDirectory() throws IOException {
        Files.createDirectories(configDir);
        log.info("配置目录已初始化: " + configDir);
    }

    private void loadOrCreateConfig() throws IOException {
        Path configFile = configDir.resolve(CONFIG_FILE);

        if (Files.notExists(configFile)) {
            createNewConfig(configFile);
        } else {
            loadExistingConfig(configFile);
        }
        validateConfig();
    }

    private void createNewConfig(Path configPath) throws IOException {
        // 使用默认配置创建新文件
        try (OutputStream out = Files.newOutputStream(configPath)) {
            defaultConfig.store(out, "AutoClicker Default Configuration");
        }
        loadDefaultValues();
    }

    private void loadExistingConfig(Path configPath) throws IOException {
        Properties fileProps = new Properties(defaultConfig);
        try (InputStream in = Files.newInputStream(configPath)) {
            fileProps.load(in);
        }
        updateHotkeyMap(fileProps);
    }

    private void updateHotkeyMap(Properties props) {
        props.forEach((keyObj, valueObj) -> {
            String key = (String) keyObj;
            String value = (String) valueObj;
            try {
                hotkeys.put(key, Integer.parseInt(value));
            } catch (NumberFormatException e) {
                System.err.println("无效的键值配置: " + key + "=" + value);
            }
        });
    }

    private void validateConfig() {
        // 确保所有默认配置都存在
        defaultConfig.forEach((keyObj, defaultValue) -> {
            String key = (String) keyObj;
            if (!hotkeys.containsKey(key)) {
                System.out.println("添加缺失的配置项: " + key);
                hotkeys.put(key, Integer.parseInt((String) defaultValue));
            }
        });
    }

    // 统一的配置访问接口
    public int getHotkey(String configKey) {
        return hotkeys.getOrDefault(configKey,
                Integer.parseInt(defaultConfig.getProperty(configKey)));
    }

    public void updateHotkey(String configKey, int newKeyCode) {
        hotkeys.put(configKey, newKeyCode);
        saveConfiguration();
    }

    private void saveConfiguration() {
        Properties props = new Properties();
        hotkeys.forEach((key, value) -> {
            props.setProperty(key, String.valueOf(value));
        });

        try (OutputStream out = Files.newOutputStream(configDir.resolve(CONFIG_FILE))) {
            props.store(out, "AutoClicker Configuration");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 扩展方法：批量更新
    public void updateHotkeys(Map<String, Integer> updates) {
        hotkeys.putAll(updates);
        saveConfiguration();
    }

    // 扩展方法：重置默认值
    public void resetToDefaults() {
        hotkeys.clear();
        updateHotkeyMap(defaultConfig);
        saveConfiguration();
    }

    private void handleConfigError(Exception e) {
        System.err.println("配置加载错误，使用默认值: " + e.getMessage());
        loadDefaultValues();
    }

    private void loadDefaultValues() {
        updateHotkeyMap(defaultConfig);
    }

    public List<HotKey> getHotkeys() {
        ArrayList<HotKey> hotKeyList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : hotkeys.entrySet()) {
            hotKeyList.add(new HotKey(entry.getKey(), NativeKeyEvent.getKeyText(entry.getValue())));
        }
        return hotKeyList;
    }

    @Data
    @AllArgsConstructor
    public static class HotKey {
        private String desc;
        private String key;
    }
}